<template>
  <div class="Container Row">
      <div class="pictureBox">
          <div class="left">
            <div class="previewContainer">
              <!--普通图片-->
              <template v-if="hoverMod.fileType === '1'">
                  <div class="img-container"
                    @mousewheel.stop="onMouseWheel"
                    @mousedown="onMouseDown"
                    @mousemove="onMouseMove"
                    @mouseleave="onMouseLeave"
                    @mouseup="onMouseUp"
                  >
                    <!-- <canvas id="canvas" width="800" height="800"></canvas> -->
                    <img :src="hoverMod.hdUrl" alt="无资源" :style="{ transform: imageTransform }" ref="imageRef">
                  </div>
                  <div class="infoBox">
                    <div class="text fileName">
                      <Tooltip :title="hoverMod.fileName" placement="top">
                        <div class="name"> {{ hoverMod.fileName  }} </div>
                      </Tooltip>
                    </div>
                    <div class="tiem">{{ `${dayjs(hoverMod.createTime).format('YYYY-MM-DD HH:mm:ss')} ${formatSize(hoverMod.fileSize)} ${hoverMod.dimension || ''}` }}</div>
                  </div>
                  <div class="operatingBox">
                      <div class="operatingBot" @click="operation('prev')">
                        <div class="iconBox">
                          <LeftCircleOutlined class="icon" />
                        </div>
                        <div class="text">前一张</div>
                      </div>
                      <div class="operatingBot" @click="operation('next')">
                        <div class="iconBox">
                          <RightCircleOutlined class="icon" />
                        </div>
                        <div class="text">后一张</div>
                      </div>
                      <div class="operatingBot" @click="operation('down')">
                        <div class="iconBox">
                          <DownloadOutlined class="icon" />
                        </div>
                        <div class="text">下载</div>
                      </div>
                      <div class="operatingBot" @click="operation('del')">
                        <div class="iconBox">
                          <DeleteOutlined class="icon" />
                        </div>
                        <div class="text">删除</div>
                      </div>
                  </div>
              </template>
              <!--视频-->
              <template v-if="hoverMod.fileType === '2'">
                  <div class="videoPlayContainer">
                    <videoPlay
                      width="100%"
                      height="100%"
                      title="预览视频"
                      :src="hoverMod.url"
                      :poster="hoverMod.hdUrl"
                    />
                  </div>
                  <div class="infoBox">
                    <div class="text fileName">
                      <Tooltip :title="hoverMod.fileName" placement="top">
                        <div class="name"> {{ hoverMod.fileName  }} </div>
                      </Tooltip>
                    </div>
                    <div class="tiem">{{ `${dayjs(hoverMod.createTime).format('YYYY-MM-DD HH:mm:ss')} ${formatSize(hoverMod.fileSize)} ${hoverMod.dimension || ''}` }}</div>
                  </div>
                  <div class="operatingBox">
                      <div class="operatingBot" @click="operation('prev')">
                        <div class="iconBox">
                          <LeftCircleOutlined class="icon" />
                        </div>
                        <div class="text">前一张</div>
                      </div>
                      <div class="operatingBot" @click="operation('next')">
                        <div class="iconBox">
                          <RightCircleOutlined class="icon" />
                        </div>
                        <div class="text">后一张</div>
                      </div>
                      <div class="operatingBot" @click="operation('down')">
                        <div class="iconBox">
                          <DownloadOutlined class="icon" />
                        </div>
                        <div class="text">下载</div>
                      </div>
                      <div class="operatingBot" @click="operation('del')">
                        <div class="iconBox">
                          <DeleteOutlined class="icon" />
                        </div>
                        <div class="text">删除</div>
                      </div>
                  </div>
              </template>
              <!--全景图-->
              <template v-if="hoverMod.fileType === '3'">
                <VuePannellum :src="hoverMod.hdUrl"></VuePannellum>
                <div class="infoBox">
                    <div class="text fileName">
                      <Tooltip :title="hoverMod.fileName" placement="top">
                        <div class="name"> {{ hoverMod.fileName  }} </div>
                      </Tooltip>
                    </div>
                    <div class="tiem">{{ hoverMod.createTime }}</div>
                  </div>
                  <div class="operatingBox">
                      <div class="operatingBot" @click="operation('prev')">
                        <div class="iconBox">
                          <LeftCircleOutlined class="icon" />
                        </div>
                        <div class="text">前一张</div>
                      </div>
                      <div class="operatingBot" @click="operation('next')">
                        <div class="iconBox">
                          <RightCircleOutlined class="icon" />
                        </div>
                        <div class="text">后一张</div>
                      </div>
                      <div class="operatingBot" @click="operation('down')">
                        <div class="iconBox">
                          <DownloadOutlined class="icon" />
                        </div>
                        <div class="text">下载</div>
                      </div>
                      <div class="operatingBot" @click="operation('del')">
                        <div class="iconBox">
                          <DeleteOutlined class="icon" />
                        </div>
                        <div class="text">删除</div>
                      </div>
                  </div>
              </template>
            </div>
            <div class="carousel">
              <a-carousel arrows :dots="false" ref="carouselRef" :infinite="false">
                <template #prevArrow>
                  <div class="custom-slick-arrow" style="left: 10px; z-index: 1" @click.prevent="prevPage">
                    <left-circle-outlined />
                  </div>
                </template>
                <template #nextArrow>
                  <div class="custom-slick-arrow" style="right: 10px" @click.prevent="nextPage">
                    <right-circle-outlined />
                  </div>
                </template>
                <div
                  class="thumbnail-container"
                  v-for="item in slidesToShow"
                  :key="item"
                >
                  <div
                    class="thumbnail"
                    :class="{ hover: ((item - 1) * visiblePageSize + indexs) === hoverIndex }"
                    v-for="(items, indexs) in slidesList(item - 1)"
                    @click.prevent="preview(item - 1, indexs)"
                    :key="indexs"
                  >
                    <img :src="items.thumbnailUrl" alt="无图" />
                  </div>
                </div>
              </a-carousel>
            </div>
          </div>
          <div class="right">
            <div class="headTitle">
              <div class="title">详细信息</div>
              <div class="close">
                <CloseOutlined @click="closeBot" style="color: white; font-size: 18px; cursor: pointer;" />
              </div>
            </div>
            <div class="infoBox">
              <div class="infoList">
                <div class="title">文件名称</div>
                <div class="content row">
                  <template v-if="editStatus">
                    <a-input 
                      ref="inputRef" v-model:value="editFileName" placeholder="请输入新的文件名称" 
                      style="color: #fff; background: #091822;  border: 1px solid #3A464E;" 
                      @pressEnter="e => handleEnter('rename', e.target.value)"
                    />
                    <CloseOutlined @click="edit('name', false)" style="color: #94989b; margin-left: 10px; font-size: 18px; cursor: pointer;" />
                  </template>
                  <template v-else>
                    <div class="text fileName">
                      <Tooltip :title="hoverMod.fileName" placement="top">
                        <div class="name"> {{ hoverMod.fileName  }} </div>
                      </Tooltip>
                    </div>
                    <EditOutlined v-if="hoverMod.fileName" @click="edit('name')" style="color: #94989b; font-size: 18px; cursor: pointer;"/>
                  </template>
                </div>
              </div>
              <div class="infoList">
                <div class="title">文件类型</div>
                <div class="text">{{ getFileType(hoverMod.fileType) }}</div>
              </div>
              <div class="infoList">
                <div class="title">任务名称</div>
                <div class="text">{{ hoverMod.jobName }}</div>
              </div>
              <div class="infoList">
                <div class="title">航线名称</div>
                <div class="text">{{ hoverMod.flightName }}</div>
              </div>
              <div class="infoList">
                <div class="title">分辨率</div>
                <div class="text">{{ hoverMod.dimension }}</div>
              </div>
              <div class="infoList">
                <div class="title">文件大小</div>
                <div class="text">{{ formatSize(hoverMod.fileSize) }}</div>
              </div>
              <div class="infoList">
                <div class="title">拍摄负载</div>
                <div class="text">{{ hoverMod.payload }}</div>
              </div>
              <div class="infoList">
                <div class="title">拍摄时间</div>
                <div class="text">{{ dayjs(hoverMod.createTime).format('YYYY-MM-DD HH:mm:ss') }} </div>
              </div>
              <div class="infoList">
                <div class="title">标签</div>
                <div class="tag-content">
                  <div class="labelTag" v-for="(item, index) in hoverMod.tags" :key="index">
                    {{ item.tag }}
                    <CloseCircleOutlined class="labelTagIcon" @click="delTag(item.id)"/>
                  </div>
                  <template v-if="editTagStatus">
                    <a-select
                      v-model:value="editTagName"
                      show-search
                      allowClear
                      placeholder="请输入标签"
                      style="width: 120px; height: 32px; margin-right: 10px; color: #fff;"
                      :default-active-first-option="false"
                      :show-arrow="false"
                      :filter-option="false"
                      :not-found-content="null"
                      :options="searchList"
                      @change="handleChange"
                      @search="handleSearch"
                    ></a-select>
                    <a-button type="primary" size="small" @click="handleSubmit">确定</a-button>
                    <CloseOutlined @click="edit('addTag', false)" style="color: #94989b; margin-left: 10px; font-size: 18px; cursor: pointer;" />
                  </template>
                  <div class="addTag" @click="edit('addTag')"  v-if="!editTagStatus">
                    <PlusOutlined class="icon" />
                    <div class="addText">标签</div>
                  </div>
                </div>
              </div>
              <template v-if="hoverMod.showMap">
                <div class="infoList">
                  <div class="title">拍摄位置</div>
                  <div class="map-wrap">
                    <div class="text"><AimOutlined /><span>当前拍摄位置</span></div>
                    <div class="map-content">
                      <!-- 地图容器 -->
                      <div id="pic-container"></div>
                    </div>
                  </div>
                </div>
              </template>
              <div class="infoList">
                <div class="title">地图显示</div>
                <div class="text">
                  <a-switch v-model:checked="hoverMod.showMap" @change="switchMap" />
                </div>
              </div>
            </div>
          </div>
      </div>
  </div>
</template>
<script lang="ts" setup>
import { inject, onMounted, computed, ref, reactive, watch, defineProps, defineEmits } from 'vue';
import dayjs from 'dayjs';
import { getfileDetail, postFileDetailList, putRenameFile, 
  postFileTagAdd, deleteFileTagDel, postSearchTag, 
  postDownloadFile, delSingleFile, getDirDictionary
} from './data.api'
import { useRouter, useRoute } from 'vue-router';
import { useMultipleTabStore } from '/@/store/modules/multipleTab';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useMessage } from '/@/hooks/web/useMessage';
import { LeftCircleOutlined, RightCircleOutlined,
  DownloadOutlined, DeleteOutlined, PlusOutlined,
  CloseOutlined , EditOutlined, AimOutlined, CloseCircleOutlined
} from '@ant-design/icons-vue';
import { videoPlay } from "/@/components/video/index";
import { Tooltip } from 'ant-design-vue';
import { VuePannellum } from '/@/components/VuePannellum';

const defaultImageOps = {
  isDragging: false,
  scale: 1,  // 图片缩放
  imageLeft: 0,
  imageTop: 0,
  dragStartX: 0,
  dragStartY: 0,
  startImageX: 0,
  startImageY: 0
}

const $http: ApiListOptions | undefined = inject('api')
const curRoute = useRoute();
const { fullPath } = curRoute;
const router = useRouter();
const tabStore = useMultipleTabStore();
const fileTypeList = ref<any[]>([])   // 文件类型的字典数据
const { createMessage , createConfirm } = useMessage();
let map = ref(); // 高德地图实例对象
let AmapObj = reactive<any>({})  // 高德地图实例对象
const emit = defineEmits();
// const imageTransform = ref<string>(''); // 图片的transform 参数
const imageRef = ref(null);
const imageOps = reactive({ ...defaultImageOps })
const hoverMod = ref<any>({}); // 激活模块
const hoverIndex = ref<number>(0); // 激活模块的索引
const pageNo = ref<number>(1);    // 页码(接口返回)
const pageSize = ref<number>(10);  // 页数(接口返回)
const pages = ref<number>(0);   // 总页数(接口返回)
const visiblePageNo = ref<number>(1); //轮播展示的页码
const visiblePageSize = 5  // 轮播展示的分页条数
const carouselRef = ref()
const fileList = ref<any[]>([]);
// 修改文件名称
const editStatus = ref<boolean>(false); // 文件名称是否处于修改状态 
const editFileName = ref<string>(''); // 临时文件名称
const inputRef = ref(null);
// 新增tag
const editTagStatus = ref<boolean>(false); // tag是否处于新增状态
const editTagName = ref<string>(''); // tag(编辑时添加的)
const inputTagRef = ref(null);
// 远程数据+模糊搜索
const searchList = ref<any[]>([])
const searchValue = ref();
let timeout: any = null;
const currentValue = ref();

// 录播的分片数量
const slidesToShow = computed(() => {
    return fileList.value.length ? Math.ceil(fileList.value.length / visiblePageSize) : 1
  }
);

const slidesList = computed(() => 
  (index) => {
    return fileList.value.length ? fileList.value.slice(index * visiblePageSize, (index + 1)* visiblePageSize ) : []
  }
);

const getFileType = computed(() =>
  (fileTypeId) => fileTypeList.value.find(item => item.value === fileTypeId)?.label || ''
);

const imageTransform = computed(() => 
`translate(${imageOps.imageLeft}px, ${imageOps.imageTop}px) scale(${imageOps.scale})`
);

onMounted(async () => {
  await initMap()
  await initData()
});

const initData = async () => {
  const result = await getDirDictionary({})
  if(Object.keys(result)?.length){
    Object.keys(result).forEach(key => {
      if(['fileType'].includes(key)){
        fileTypeList.value = result[key]
      }
    });
  }
  const res = await postFileDetailList({
    fileId: curRoute.query.fileId, 
    dirId: curRoute.query.dirId, 
    dirPageNo: curRoute.query.dirPage, 
    dirPageSize: curRoute.query.dirPageSize
  })
  const { data = {} } = res
  //console.log("data", data)
  if( data?.code === 200 && data?.result) {
    pageNo.value = data?.result?.current
    pages.value = data?.result?.pages
    pageSize.value = data?.result?.size
    fileList.value = data?.result?.records || []
    const fileListTemp = fileList.value
    if(fileListTemp?.length){
      const hoverIndex = fileListTemp.findIndex(item => item.fileId === curRoute.query.fileId)
      //console.log("hoverIndex--------", hoverIndex)
      if(hoverIndex !== -1){
        if(hoverIndex >= visiblePageSize){
          visiblePageNo.value = Math.ceil((hoverIndex + 1) / visiblePageSize)
          //console.log("初始化--visiblePageNo.value", visiblePageNo.value)
          carouselRef.value.goTo(visiblePageNo.value - 1)
        }else{
          visiblePageNo.value = 1
        }
        updateCurImage(hoverIndex)
      }else{
        visiblePageNo.value = 1
        updateCurImage(0)
      }
    }
  }
}

const initMap = async () => {
  try{
    const AMap = await AMapLoader.load({
      "key": "59c61f064c552f2ace25ff0c1d6465a7",  // 申请好的Web端开发者Key，首次调用 load 时必填
      "version": "2.0",   // 指定要加载的 JS API 的版本，缺省时默认为 1.4.15
      "plugins": [],      // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
    AmapObj = AMap
    //console.log("加载完地图---------------")
    map.value = new AMap.Map('pic-container', {
        center: [114.118725, 22.697947],
        zoom: 16,
        viewMode: '3D',//使用3D视图
    })
  }catch(e){
    console.log("地图初始化", e)
  }
}

//更新地图
const handleChangeMap = (lng, lat) => {
  //console.log("更新地图==map", AmapObj, map.value)
  if(lng && lat){
    const position = new AmapObj.LngLat(lng, lat)
    map.value.setZoomAndCenter(16, position) // 传入经纬度，设置地图中心点
  }else{
    if( typeof map.value !== 'undefined'){
      map.value.clearMap()
    }
  }
}

// 格式化文件大小
const formatSize = (size) => {
  const isM = size >= (1024 * 1024)
  const isKB = size >= 1024
  const text = size ? isM ? (size  / (1024 * 1024)).toFixed(2) : isKB ? (size  / (1024 )).toFixed(2) : Number(size || 0) ? size.toFixed(2) : 0 : 0
  return `${text}${isM ? 'M' : isKB ? 'KB' : 'B'}`
}

// 图片的缩放和拖动
function onMouseWheel(event) {
  event.preventDefault();
  const wheelDelta = event.deltaY;
  if (wheelDelta > 0 && imageOps.scale > 0.4) {
    imageOps.scale -= 0.1;
  } else if (wheelDelta < 0) {
    imageOps.scale += 0.1;
  }
}
function onMouseDown(event) {
  imageOps.isDragging = true;
  imageOps.dragStartX = event.clientX;
  imageOps.dragStartY = event.clientY;
  imageOps.startImageX = imageOps.imageLeft;
  imageOps.startImageY = imageOps.imageTop;
}
function onMouseMove(event) {
  event.preventDefault();
  if (imageOps.isDragging) {
    const offsetX = event.clientX - imageOps.dragStartX;
    const offsetY = event.clientY - imageOps.dragStartY;
    imageOps.imageLeft = imageOps.startImageX + offsetX;
    imageOps.imageTop = imageOps.startImageY + offsetY;
  }
}
function onMouseUp() {
  imageOps.isDragging = false;
}
function onMouseLeave() {
  imageOps.isDragging = false;
}

// 重置缩放参数 / 退出编辑状态
const resetImageOpsAndEdit = () => {
  Object.keys(defaultImageOps).forEach(key =>
    imageOps[key] = defaultImageOps[key]
  )
  editTagStatus.value = false
  editTagName.value = ''
  editStatus.value = false
  editFileName.value = ''
}

// 更新文件的列表查询
const updateFileListDetail = async (newPageNo: number, pageType: string) => {
  const res = await postFileDetailList({
    dirId: curRoute.query.dirId,
    pageNo: newPageNo,
    pageSize: pageSize.value
  })
  const { data = {} } = res
  //console.log("data", data)
  if( data?.code === 200 ){
    if(data?.result && data?.result?.records?.length) {
      const pageNoTemp = pageNo.value
      pageNo.value = newPageNo
      fileList.value = data?.result?.records || []
      const fileListTemp = fileList.value
      if(fileListTemp?.length){  
        if(pageType === 'prevPage'){  // 操作的是'上一页'则激活最后一条数据
          const hoverIndexTemp = fileListTemp?.length - 1
          if(hoverIndexTemp >= visiblePageSize){
            visiblePageNo.value = Math.ceil((hoverIndexTemp + 1) / visiblePageSize)
            carouselRef.value.goTo(visiblePageNo.value - 1)
          }
          updateCurImage(hoverIndexTemp)
        }else if(pageType === 'nextPage'){  // 操作的是'下一页'则激活第一条数据
          visiblePageNo.value = 1
          carouselRef.value.goTo(0)
          updateCurImage(0)
        }else if(pageType === 'curPage'){ // 更新当前页则激活索引不变
          let hoverIndexTemp =  hoverIndex.value
          if(hoverIndexTemp > fileListTemp?.length - 1 || pageNoTemp !== pageNo.value) hoverIndexTemp =  fileListTemp?.length - 1
          if(hoverIndexTemp >= visiblePageSize){
            visiblePageNo.value = Math.ceil((hoverIndexTemp + 1) / visiblePageSize)
            carouselRef.value.goTo(visiblePageNo.value - 1)
          }
          //console.log("删除数据--hoverIndexTemp", hoverIndexTemp)
          updateCurImage(hoverIndexTemp)
        }
      }
    }else{
      if( newPageNo - 1 >= 1){
        updateFileListDetail( newPageNo - 1, pageType)  // 当前页没有数据则递归取上一页数据
      }
    }
  }
}

// 更新当前操作的文件信息(单个)
const updateCurFileDetail = async () => {
  const res = await getfileDetail({ id: hoverMod.value.fileId })
  const { data = {} } = res
  if( data?.code === 200 && data?.result) {
    const fileListTemp = fileList.value
    const index = fileListTemp.findIndex(item => item.fileId === hoverMod.value.fileId)
    fileListTemp[index] = data?.result
    hoverMod.value = fileListTemp[index]
    fileList.value = fileListTemp
  }else{
    createMessage.warning(data.message)
  }
}

// 更新激活的图片
const updateCurImage = (curHoverIndex) => {
  const fileListTemp = fileList.value
  hoverIndex.value = curHoverIndex
  hoverMod.value = fileListTemp?.length ? fileListTemp[curHoverIndex] ? fileListTemp[curHoverIndex] : fileListTemp[0] : []
  if(!fileListTemp[curHoverIndex]){
    carouselRef.value.goTo(0)
  }
  resetImageOpsAndEdit()
  //更新地图
  handleChangeMap(hoverMod.value?.shootPosition?.lng, hoverMod.value?.shootPosition?.lat)
}

const operation = async (type: string) => {
  switch(type){
    case 'prev':  // 前一张
      {
        const hoverIndexTemp =  hoverIndex.value
        const pageNoTemp = visiblePageNo.value
        if(hoverIndexTemp === 0){
          if(pageNo.value <= 1) {
            createMessage.warning("已是第一张")
            return
          }
          updateFileListDetail(pageNo.value - 1, 'prevPage')
          return
        }
        if(hoverIndexTemp - 1 < (pageNoTemp - 1) * visiblePageSize){
          //console.log("滑块的上一页")
          carouselRef.value.prev()
          visiblePageNo.value = pageNoTemp - 1
          const curHoverIndex = (pageNoTemp - 1) * visiblePageSize - 1
          updateCurImage(curHoverIndex)
          return
        }
        updateCurImage(hoverIndexTemp - 1)
      }
      break;
    case 'next':  // 后一张
      {
        const hoverIndexTemp =  hoverIndex.value
        const pageNoTemp = visiblePageNo.value
        if(hoverIndexTemp === fileList.value?.length - 1){
          if( pageNo.value === pages.value){
            createMessage.warning("已是最后一张")
            return
          }
          // 更新列表
          updateFileListDetail(pageNo.value + 1, 'nextPage')
          return
        }
        if(hoverIndexTemp + 1 >= pageNoTemp * visiblePageSize){
          //console.log("滑块的下一页")
          carouselRef.value.next()
          visiblePageNo.value = pageNoTemp + 1
          const curHoverIndex = pageNoTemp * visiblePageSize
          updateCurImage(curHoverIndex)
          return
        }
        updateCurImage(hoverIndexTemp + 1)
      }
      break;
    case 'down':  // 下载
      const res = await postDownloadFile({ id: hoverMod.value.fileId })
      const { data = {} } = res
      if( data?.code === 200 && data?.result) {
        var down = document.createElement("a");
        down.href = data.result;
        down.target = "_self";
        document.body.appendChild(down);
        down.click();
        document.body.removeChild(down);
      }else{
        createMessage.warning(data.message)
      }
      break;
    case 'del':  // 删除
      {
        createConfirm({
          title: '删除文件',
          content: '确定要删除文件吗？',
          iconType: 'warning',
          onOk: async () => {
            const res = await delSingleFile({ id: hoverMod.value.fileId })
            //console.log("删除文件==res", res)
            const { data = {} } = res
            if( data.code === 200) {
              // 删除成功后拉取接口更新数据
              updateFileListDetail(pageNo.value, 'curPage')
            }else{
              createMessage.warning(data.message)
            }
          },
          onCancel: () => {},
        });
      }
      break;
  }
}

const preview = (index, indexs) => {
  //console.log("index, indexs", index, indexs)
  const curHoverIndex = index * visiblePageSize + indexs
  updateCurImage(curHoverIndex)
}

// 上一页
const prevPage = () => {
  const fileListTemp = fileList.value
  const pageNoTemp = visiblePageNo.value
  if(fileListTemp?.length){
    if(pageNoTemp === 1){
      // 更新列表
      if(pageNo.value <= 1) {
        createMessage.warning("已是第一页")
        return
      }
      updateFileListDetail(pageNo.value - 1, 'prevPage')
      return
    }
    visiblePageNo.value = pageNoTemp - 1
  }
}

// 下一页
const nextPage = () => {
  const fileListTemp = fileList.value
  const pageNoTemp = visiblePageNo.value
  if(fileListTemp?.length){
    //console.log("下一页", pageNoTemp + 1, Math.ceil(fileListTemp?.length / visiblePageSize))
    if(pageNoTemp + 1 > Math.ceil(fileListTemp?.length / visiblePageSize) ){
      if( pageNo.value === pages.value){
        createMessage.warning("已是最后一页")
        return
      }
      // 更新列表
      updateFileListDetail(pageNo.value + 1, 'nextPage')
      return
    }
    visiblePageNo.value = pageNoTemp + 1
  }
}

/**  
 * 编辑文件信息
 * @param {string} type 激活的字段(类型)
 * @param {boolean} isEdit 激活/退出编辑状态
 * 
*/
const edit = (type: string, isEdit: boolean = true) => {
  switch(type){
    case 'name':  // 编辑文件名称
      if(isEdit){
        editStatus.value = true
        editFileName.value = hoverMod.value.fileName.substring(0, hoverMod.value.fileName.lastIndexOf("."))
        inputRef.value && inputRef.value.focus();
      }else{
        editStatus.value = false
        editFileName.value = ''
      }
      break;
    case 'addTag':  // 新增tag
      if(isEdit){
        editTagStatus.value = true
        searchValue.value = ''
        inputTagRef.value && inputTagRef.value.focus();
      }else{
        editTagStatus.value = false
        editTagName.value = ''
      }
      break;
  }
}

const handleEnter = async (type: string, value: any) => {
  if(!value) return
  switch(type){
    case "rename":  // 变更文件名称
      {
        // console.log("变更文件名称--e", value)
        const res = await putRenameFile({ 
          id: hoverMod.value.fileId, 
          newName: `${value}.${hoverMod.value.fileName.substring(hoverMod.value.fileName.lastIndexOf(".") + 1)}`, 
          oldName: hoverMod.value.fileName
        })
        const { data = {} } = res
        if( data.code === 200) {
          editStatus.value = false
          editFileName.value = ''
          updateCurFileDetail()
        }else{
          createMessage.warning(data.message)
        }
      }
      break
    case "addTag":   //新增标签
      {
        const res = await postFileTagAdd({ fileId: hoverMod.value.fileId, tag: value })
        const { data = {} } = res
        if( data.code === 200) {
          editTagStatus.value = false
          editTagName.value = ''
          searchValue.value = ''
          searchList.value = []
          updateCurFileDetail()
        }else{
          createMessage.warning(data.message)
        }
      }
      break
  }
}

// 删除标签
const delTag = async (tagId) => {
  const res = await deleteFileTagDel({ id: tagId })
  const { data = {} } = res
  if( data.code === 200) {
    editTagStatus.value = false
    editTagName.value = ''
    updateCurFileDetail()
  }else{
    createMessage.warning(data.message)
  }
}

const searchData = (value: string, callback: any) => {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }

  currentValue.value = value;
  
  const fetch = async() => {
    const res = await postSearchTag({ tag: value })
    const { data = {} } = res
    if( data.code === 200) {
      if (currentValue.value === value) {
        const result = data.result || []
        const resData: any[] = result.map( (item, index) => {
          return {
            value: index + 1,  // 后端给的id都为null,前端自定义下唯一标识
            label: item.tag,
          }
        });
        callback(resData);
      }
    }
  }
  timeout = setTimeout(fetch, 300)
}

const handleSearch = (val: any) => {
  //console.log("handleSearch--data", val)
  if(val){
    searchValue.value = val
    searchData(val, (d: any[]) => (searchList.value = d));
  }
};

const handleChange = (val: any) => {
  //console.log("handleChange--data", val)
  searchValue.value = val
};

const handleSubmit = () => {
  //console.log("handleSubmit--data", searchValue.value, searchList.value)
  let tagText = ''
  const item = searchList.value.find(item => item.value == searchValue.value)?.label
  if(item){
    tagText = item
  }else if(searchValue.value){
    tagText = searchValue.value
  }
  //console.log("新增标签--", tagText)
  if(tagText){
    handleEnter('addTag', tagText)
  }
}

function closeBot() {
  resetData()
  // 回退到列表页
  tabStore.closeTabByKey(fullPath, router);
  // router.push({
  //   path: '/dataManage/dataManage'
  // })
}

const switchMap = async (checked: boolean) => {
  //console.log("checked", checked)
  const result = await $http.putManageShowMap({ fileId: hoverMod.value.fileId, showMap: Number(checked) })
  if(!result){
    hoverMod.value.showMap = !checked
  }
}

const resetData = () => {
  hoverMod.value = {}
  hoverIndex.value = 0
  pageNo.value = 1
  pageSize.value = 10
  visiblePageNo.value = 1
  fileList.value = []
  editStatus.value = false
  editFileName.value = ''
  editTagStatus.value = false
  editTagName.value = ''
  searchValue.value = ''
  searchList.value = []
  resetImageOpsAndEdit()
}

</script>
<style lang="less" scoped>
/deep/ .scrollbar__wrap {
  overflow: inherit;
}
/* For carousel */
:deep(.slick-slide) {
  text-align: center;
  height: 140px;
  line-height: 140px;
  background: #000;
  overflow: hidden;
}
:deep .ant-select-clear {
  color: #fff;
  background: #000;
}

:deep(.slick-arrow.custom-slick-arrow) {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #fff;
  background-color: rgba(31, 45, 61, 0.11);
  transition: ease all 0.3s;
  // opacity: 0.3;
  z-index: 1;
}
:deep(.slick-arrow.custom-slick-arrow:before) {
  display: none;
}
:deep(.slick-arrow.custom-slick-arrow:hover) {
  color: #fff;
  opacity: 0.5;
}
:deep(.slick-slide h3) {
  color: #fff;
}

.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}

.Container{width: 100%;height: 100%;position: relative;}
.Container>*{min-width: 30px;position: absolute;top:0;height: 100%;}
.Row{ display: flex; flex-direction: row; }
    .pictureBox {
        width: 100%;
        height: 100%;
        padding: 15px 15px 0px;
        display: flex;
        .left {
          width: 73%;
          height: 100%;
          background-color: #091822;
          .previewContainer{
            position: relative;
            height: calc(100% - 140px);
            .img-container{
              width: 100%;
              height: 100%;
              overflow: hidden;
              >img{
                width: 100%;
                height: 100%;
              }
            }
            .videoPlayContainer{
              width: 100%;
              height: 100%;
            }
            .infoBox {
              width: 410px;
              height: 81px;
              background: linear-gradient(90deg, rgba(0, 0, 0, 0.3) 0%, rgba(0, 0, 0, 0) 100%);
              backdrop-filter: blur(2px);
              padding: 15px 18px;
              position: absolute;
              top: 24px;
              left: 32px;
              z-index: 999;
              .text {
                font-size: 20px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #FFFFFF;
                line-height: 28px;
                width: 390px;
                &.fileName{
                  flex-wrap: nowrap;
                  .name{
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  }
                  // .ext{

                  // }
                }
              }
              .tiem {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #FFFFFF;
                opacity: 0.7;
                line-height: 20px;
              }
            }
            .operatingBox {
              width: 373px;
              height: 44px;
              background: rgba(21, 21, 21, 0.4);
              border-radius: 4px;
              backdrop-filter: blur(5px);
              position: absolute;
              left: 50%;
              bottom: 20px;
              transform: translate(-50%, -50%);
              display: flex;
              justify-content: space-around;
              align-items: center;
              padding: 0 25px;
              z-index: 999;
              .operatingBot {
                display: flex;
                align-items: center;
                cursor: pointer;
                .iconBox {
                  display: flex;
                  align-items: center;
                  margin-right: 7px;
                  .icon {
                    font-size: 18px;
                    color: #FFFFFF;
                  }
                }
                .text {
                  font-size: 14px;
                  font-family: PingFangSC-Regular, PingFang SC;
                  font-weight: 400;
                  color: #FFFFFF;
                }
              }
            }
          }
          .carousel{
            height: 140px;
            /deep/.thumbnail-container{
              width: 100%;
              height: 140px;
              display: flex !important;
              align-items: center;
              padding: 0 60px;
              .thumbnail{
                width: 170px !important;
                height: 90px;
                margin-right: 25px;
                img{
                  width: 100%;
                  height: 100%;
                }
                &.hover{
                  img{
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                    border: 4px solid #1a9efd;
                  }
                }
              }
            }
          }
        }
        .right {
          width: 27%;
          height: 100%;
          background-color: #091822;
          .headTitle {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 12px;
            padding: 12px 14px 14px 22px;
            .title {
              font-size: 16px;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 500;
              color: #FFFFFF;
            }
            .close {
              width: 40px;
              height: 40px;
              background-color: #3c454b;
              border-radius: 8px;
              display: flex;
              align-items: center;
              justify-content: center;
              // opacity: 0.39;
            }
          }
          .infoBox {
            padding: 0 22px;
            .infoList {
              display: flex;
              // align-items: center;
              margin-bottom: 16px;
              .title {
                width: 70px;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #7b8388;
                margin-right: 19px;
              }
              .text {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                width: 226px;
                color: #FFFFFF;
                display: flex;
                flex-wrap: wrap;
                align-items: flex-start;
                &.fileName{
                  flex-wrap: nowrap;
                  .name{
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  }
                  // .ext{

                  // }
                }
                
              }
              .tag-content{
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                :deep(.ant-select-selector){
                    background: #091822;
                    border: 1px solid #3A464E;
                  }
                .labelTag {
                  position: relative;
                  padding: 5px 7px;
                  background: rgba(216, 216, 216, 0.06);
                  color: #fff;
                  display: inline-block;
                  border-radius: 2px;
                  margin-right: 10px;
                  margin-bottom: 5px;
                  &:hover{
                    .labelTagIcon{
                      display: block;
                      color: rgb(179 182 189);
                    }
                  }
                  .labelTagIcon{
                    display: none;
                    position: absolute;
                    width: 15px;
                    height: 15px;
                    right: -5px;
                    top: -5px;
                  }
                }
                .addTag {
                  padding: 4px 10px;
                  background: rgba(216, 216, 216, 0.06);
                  border-radius: 2px;
                  display: flex;
                  align-items: center;
                  width: 75px;
                  justify-content: space-between;
                  border: 1px dashed rgba(255, 255, 255, 0.2);
                  cursor: pointer;
                  .icon {
                    margin-right: 6px;
                    color: #c2c6c8;
                  }
                  .addText {
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #adb1b6;
                  }
                }
              }
              .content{
                display: flex;
                &.row{
                  align-items: center;
                }
                &.col{
                  flex-direction: column;
                }
              }
              .map-wrap{
                height: 230px;
                .text{
                  display: flex;
                  align-items: center;
                  span{
                    margin-left: 10px;
                  }
                }
                .map-content{
                    width: 220px;
                    height: 200px;
                    #pic-container {
                      width: 220px;
                      height: 200px;
                    }
                }
              }
            }
          }
        }
    }
</style>
